package com.example.blue;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.nfc.Tag;
import android.os.Binder;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// BluetoothService.java
public class BluetoothService extends Service {
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothGatt bluetoothGatt;
    private BluetoothDevice connectedDevice;
    private volatile boolean isConnected = false;
    private String TAG="bluetooth service";
    // Binder 用于 Activity 绑定服务并通信
    private final IBinder binder = new LocalBinder();
    private static final UUID SERVICE_UUID = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e"); // 示例：设备信息服务
    // TODO: 将此处的 UUID 替换为你想要接收通知的特征的 UUID
    private static final UUID CHARACTERISTIC_UUID = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e"); // 示例：制造商名称特征
    private static final UUID CCC_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
    private StringBuffer saveData = new StringBuffer();
    private Integer saveNum=0;
    private Boolean isSaved=false;
    private HandlerThread gattThread;
    private Handler gattHandler;
    private final ConcurrentLinkedQueue<byte[]> dataQueue = new ConcurrentLinkedQueue<>();
    public static final String ACTION_CONNECTED = "com.example.bluetooth.ACTION_CONNECTED";
    public static final String ACTION_DISCONNECTED = "com.example.bluetooth.ACTION_DISCONNECTED";
    public static final String ACTION_DATA_AVAILABLE = "com.example.bluetooth.ACTION_DATA_AVAILABLE";
    private Boolean isSendBroadcast=false;

    public class LocalBinder extends Binder {
        public BluetoothService getService() {
            return BluetoothService.this;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }
    public ConcurrentLinkedQueue<byte[]> getDataQueue() {

        return dataQueue;
    }

    /** 接收 BLE 数据时调用（假设 BLE 回调触发这里） */
//    public void onBleDataReceived(String data) {
//        dataQueue.add(data); // 存入队列
//    }

    /** Activity 调用，批量取数据 */
//    public List<String> fetchDataBatch() {
//        List<String> batch = new ArrayList<>();
//        while (!dataQueue.isEmpty()) {
//            batch.add(dataQueue.poll());
//        }
//        return batch;
//    }


    @Override
    public void onCreate() {
        Log.i("Tag","start service");
        super.onCreate();
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        gattThread = new HandlerThread("BluetoothGattThread");
        gattThread.start();
        gattHandler = new Handler(gattThread.getLooper());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 可以从 Intent 中获取需要连接的设备地址等信息并连接
        String deviceAddress = intent.getStringExtra("DEVICE_ADDRESS");
        Log.i("-------------Tag---------------",deviceAddress);
        if (deviceAddress != null) {
            new Thread(() -> {
                // 耗时操作，比如蓝牙连接
                try {
                    connectToDevice(deviceAddress);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }).start();
        }
        // START_STICKY 表示服务被异常杀死后尝试重新创建
        return START_STICKY;
    }


    private void connectToDevice(String deviceAddress) throws IOException {

        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
        if (bluetoothGatt != null) {
            bluetoothGatt.close();
        }
        connectedDevice = bluetoothAdapter.getRemoteDevice(deviceAddress);
        bluetoothGatt = connectedDevice.connectGatt(this, false, gattCallback);

    }
    public boolean saveToExternalStorage(String fileName, String content) {
        // 检查外部存储是否可用
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Log.e("FileSave", "外部存储不可用");
            return false;
        }

        File file = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOCUMENTS), fileName);

        try {
            // 确保目录存在
            File parent = file.getParentFile();
            if (!parent.exists() && !parent.mkdirs()) {
                Log.e("FileSave", "创建目录失败");
                return false;
            }

            FileWriter writer = new FileWriter(file);
            writer.write(content);
            writer.close();

            Log.d("FileSave", "文件保存成功: " + file.getAbsolutePath());
            return true;
        } catch (IOException e) {
            Log.e("FileSave", "保存文件时出错: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                // 连接成功
                Log.d(TAG, "成功连接到 GATT 服务器");
                Intent intent = new Intent(ACTION_CONNECTED);
                sendBroadcast(intent);
                gatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                // 连接断开
                Intent intent = new Intent(ACTION_DISCONNECTED);
                sendBroadcast(intent);
                Log.d(TAG, "与 GATT 服务器断开连接");
                gatt.close();
            }
        }
        @Override
        public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
            Log.d("BLE", "MTU changed: " + mtu);
        }
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.d(TAG, "服务发现成功");
                //  handler.post(() -> statusTextView.setText("服务发现成功！正在订阅通知..."));
                // 查找特定的服务和特征
                BluetoothGattCharacteristic characteristic = findCharacteristic(gatt);
                if (characteristic != null) {
                    // 启用通知
                    gatt.setCharacteristicNotification(characteristic, true);
                    // 写入描述符以启用通知
                    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CCC_UUID);

                    if (descriptor != null) {
                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                        gatt.writeDescriptor(descriptor);
                    }
                } else {
                    //  handler.post(() -> statusTextView.setText("未找到所需的特征。"));
                }
            } else {
                Log.e(TAG, "服务发现失败，状态码：" + status);
                // handler.post(() -> statusTextView.setText("服务发现失败。"));
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            // 接收到通知数据
             byte[] data =  characteristic.getValue();
             if(isSendBroadcast==false) {
                 Intent intent = new Intent(ACTION_DATA_AVAILABLE);
                 sendBroadcast(intent);
                 isSendBroadcast=true;
             }
            //System.out.println(data.toString());
            dataQueue.add(data);

        }


        private BluetoothGattCharacteristic findCharacteristic(BluetoothGatt gatt) {
            // 遍历所有服务，找到匹配的 UUID
            for (android.bluetooth.BluetoothGattService service : gatt.getServices()) {
                if (service.getUuid().equals(SERVICE_UUID)) {
                    // 找到目标服务，遍历其特征
                    return service.getCharacteristic(CHARACTERISTIC_UUID);
                }
            }
            return null;
        }
    };
//    private void processData(byte[] data) {
//        // 这里处理接收到的数据
//       // Handler mainHandler = new Handler(Looper.getMainLooper());
//            gattHandler.post(() -> {
//            // 更新UI
//            if (data != null && data.length > 0) {
//                // 将原始数据转换为十六进制字符串
////                final StringBuilder stringBuilder = new StringBuilder(data.length);
////                for (byte byteChar : data) {
////                    stringBuilder.append(String.format("%02X ", byteChar));
////                }
////                final String hexData = stringBuilder.toString().trim(); // 去除末尾空格
//                String hexData = bytesToHex(data);
//                dataQueue.add(hexData);
////                System.out.println(saveNum+" "+hexData);
////                saveNum+=1;
////                if(saveNum>10000 && saveNum<12000){
////                   // Log.d(TAG,  saveNum.toString());
////                    saveData.append(saveNum.toString()+" "+hexData+"\n");
////
////                }else if(isSaved==false && saveNum==12000) {
////                    saveToExternalStorage("parkinson-bluedata.txt", saveData.toString());
////                    isSaved=true;
////                }
//            }
//        });
//
//        // 或者使用 LiveData 发送数据到UI
//        // dataLiveData.postValue(data);
//    }
    public static String bytesToHex(byte[] bytes) {
        if (bytes == null) return null;

        char[] hexChars = new char[bytes.length * 3]; // 每个字节需要3个字符(2个十六进制+1个空格)
        for (int i = 0; i < bytes.length; i++) {
            int v = bytes[i] & 0xFF; // 将字节转换为无符号整数

            // 高位4位
            hexChars[i * 3] = "0123456789ABCDEF".charAt(v >>> 4);
            // 低位4位
            hexChars[i * 3 + 1] = "0123456789ABCDEF".charAt(v & 0x0F);
            // 添加空格分隔符
            hexChars[i * 3 + 2] = ' ';
        }
        return new String(hexChars, 0, hexChars.length - 1); // 移除最后一个空格
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    // 子线程：接收和发送数据

}

